/*
* Copyright 2016 YONYOU Corporation Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project         marketing

* @Package         com.yonyou.marketing.wechat.api.config

* @Author          LuZhen

* @FileName        MyErrorDecoder

* @Date            2016/11/30

----------------------------------------------------------------------------------
*     Date          Who             Version         Comments
* 1. 2016/11/30        LuZhen          1.0             Create Source
*
----------------------------------------------------------------------------------
*/
package org.marketing.common.hystrix;

import com.netflix.hystrix.exception.HystrixBadRequestException;

import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpStatusCodeException;

import static feign.FeignException.errorStatus;

@Configuration
public class MyErrorDecoder implements ErrorDecoder {

	private static Logger logger=Logger.getLogger(MyErrorDecoder.class);
    @Override
    public Exception decode(String methodKey, Response response) {
    	logger.info("--------------------,MyErrorDecoder,common,");
    	String mes="";
    	try{
        	Exception x=errorStatus(methodKey, response);
        	mes=x.getMessage();
        	mes=mes.substring(mes.indexOf("content:")+9);
    	}catch(Exception ex){
    		mes="unknow exception";
    	}
    	
    	Exception e=new MarketingBizException(mes);
        if (response.status()== 400) {
            return new HystrixBadRequestException(response.body().toString(),e);
        }
        if (response.status()== 417) {
        	logger.info("--------------------,MyErrorDecoder,common,"+response.status());
            return new HystrixBadRequestException("my decoder error",e);
        }
        return errorStatus(methodKey, response);
    }
}
